// 路由权限处理

import router from '@/router'
import { routes } from '@/router'
import store from '@/store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

import { getSessionStorage } from '@/utils/auth.js'
// 关闭圆形的指示器
NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/404']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const { info } = store.state.user
  const user = getSessionStorage('user')

  if (user) {
    if (!info.name) {
      store.dispatch('user/setLogin', user)
      router.addRoutes([
        ...routes,
        { path: '*', redirect: '/404', hidden: true },
      ])
      next({ ...to, replace: true })
    }

    if (to.path == '/login') {
      next('/')

      NProgress.done()
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')

      NProgress.done()
    }
  }
})

// 路由发生跳转，在跳转前后执行afterEach
router.afterEach(() => {
  NProgress.done()
})
